﻿using JobSearcherAPI.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace JobSearcherAPI.Search
{
    internal abstract class JsonSearcher : SearcherBase
    {
        protected JToken token;

        protected abstract override string CreateSearchAddress(SearchArguments arguments);
        protected abstract override void SetUpAttributeStrings();

        // Override to make token have all target children
        protected abstract void CreateToken(string json);

        public JsonSearcher()
        {
            SetUpAttributeStrings();
        }

        public override async Task<SearchResult> Search(SearchArguments arguments)
        {
            searchAddress = CreateSearchAddress(arguments);
            var result = new SearchResult();
            Uri addressUri = new Uri(searchAddress);

            using (var client = new WebClient())
            {
                client.DownloadStringCompleted += (sender, e) =>
                {
                    CreateToken(e.Result);

                    foreach (JToken t in token.Children())
                    {
                        var job = new Job
                        {
                            Title = (string)t.SelectToken(title),
                            Description = (string)t.SelectToken(description),
                            Company = (string)t.SelectToken(company),
                            Location = (string)t.SelectToken(location),
                            PostDate = DateTime.Now,
                            PostURL = (string)t.SelectToken(url)
                        };
                        result.Add(job);
                    }
                };
                await client.DownloadStringTaskAsync(addressUri);
                return result;
            }


        }
    }
}
